package com.example.plugins.routes

import com.example.plugins.DistributorDto
import com.example.plugins.DistributorRepo
import com.example.plugins.ExposedDistributorRepo
import com.example.plugins.UserSession
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*

fun Route.distributorRouting() {
    val distributorRepo: DistributorRepo = ExposedDistributorRepo()

    get("/login") {
        call.sessions.set(UserSession(id = "123abc", count = 0))
        call.respondRedirect("/user")
    }

    get("/user") {
        val userSession = call.sessions.get<UserSession>()
        if (userSession != null) {
            call.sessions.set(userSession.copy(count = userSession.count + 1))
            call.respondText("Session ID is ${userSession.id}. Reload count is ${userSession.count}.")
        } else {
            call.respondText("Session doesn't exist or is expired.")
        }
    }

    get("/logout") {
        call.sessions.clear<UserSession>()
        call.respondRedirect("/user")
    }

    route("/distributors") {
        get {
            call.respond(HttpStatusCode.OK, distributorRepo.getAll())
        }

        get("{id?}") {
            val id = call.parameters["id"]?.toLongOrNull()

            if (id == null) {
                call.respond(HttpStatusCode.BadRequest, "нет такого id")

                return@get
            }

            val distributor = distributorRepo.getByIdOrNull(id.toInt())

            if (distributor == null) {
                call.respond(HttpStatusCode.NotFound)

                return@get
            }

            call.respond(HttpStatusCode.OK, message = distributor)
        }

        get("{id?}/{coal-id?}"){
            val id = call.parameters["id"]?.toIntOrNull()

            val coalId = call.parameters["coal-id"]?.toIntOrNull()

            if (id == null) {
                call.respond(HttpStatusCode.BadRequest, "нет такого id")

                return@get
            }

            val distributor = distributorRepo.getByIdOrNull(id)

            if (distributor == null) {
                call.respond(HttpStatusCode.NotFound)

                return@get
            }

            if (coalId == null) {
                call.respond(HttpStatusCode.BadRequest, "нет такого coal_id")

                return@get
            }

            val coalDto = distributor.coalItems.singleOrNull { it.id == coalId }

            if (coalDto == null) {
                call.respond(HttpStatusCode.NotFound, "Distributor does not have such coal item")

                return@get
            }

            call.respond(HttpStatusCode.OK, coalDto)
        }

        post {
            val distributor = call.receive<DistributorDto>()

            distributorRepo.create(distributor.name , distributor.address)

            call.respondText("Distributor has been added", status = HttpStatusCode.Created)
        }

        delete("{id?}") {
            val distributorId = call.parameters["id"]?.toIntOrNull();

            if (distributorId == null) {
                call.respond(HttpStatusCode.BadRequest, "Wrong distributor id param")

                return@delete
            }

            if (distributorRepo.getByIdOrNull(distributorId) == null) {
                call.respond(HttpStatusCode.NotFound, "Distributor does not exist")

                return@delete
            }

            distributorRepo.delete(distributorId)

            call.respond(HttpStatusCode.NoContent, "Distributor has been deleted")
        }
    }
}


